package com.Policing.Login;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.annotation.Nullable;
import android.util.Log;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.Policing.Ip_set.Ip_Set;
import com.Policing.JavaBean.LoginJavaBean;
import com.Policing.LogUtils;
import com.Policing.Okhttps.MyOkHttp;
import com.Policing.R;
import com.Policing.Since_case.Since_case;
import com.Policing.menu.HomeActivity;
import com.Policing.menu.SlideSideMenuExampleActivity;
import com.gg.reader.api.utils.HksPower;
import com.google.gson.Gson;
import com.hb.dialog.dialog.LoadingDialog;
import com.hb.dialog.myDialog.MyAlertInputDialog;
import com.tencent.android.tpush.XGIOperateCallback;
import com.tencent.android.tpush.XGPushManager;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Response;

/**
 * Created by Administrator on 2018/12/26.
 */

public class login extends Activity {
    private EditText user;
    private EditText password;
    private Button login;
    private int i = 0;
    private SharedPreferences jz;
    private String url;
    LoadingDialog loadingDialog;
    private CheckBox checkBox;
    private TextView setip;
    private MyOkHttp myOkHttp;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_logo_activty);
        // Log.i("123123",sHA1(this)+"");
        myOkHttp = new MyOkHttp(login.this);
        SharedPreferences mm = getSharedPreferences("mm", Context.MODE_PRIVATE);//1.通过上下文得到
        String ipip = mm.getString("ipip", "");
        Log.d("进来了吗", "ipip: " + ipip);
        if (!ipip.equals("")) {
            Ip_Set ipSet = new Ip_Set();
            ipSet.setIP(ipip);
        }
        url = "http://" + Ip_Set.IP + "/api/login";
        Log.d("进来了吗", "ipip: " + Ip_Set.IP);
        inview();
        String yy = mm.getString("b", "");
        if (yy.equals("1")) {
            checkBox.setChecked(true);
            user.setText(mm.getString("user", ""));
            password.setText(mm.getString("password", ""));
        } else if (yy.equals("0")) {
            checkBox.setChecked(false);
            user.setText("");
            password.setText("");
        }
        login.setOnClickListener(v -> {
            /*Intent inten = new Intent(login.this, HomeActivity.class);
            startActivity(inten);
            finish();*/
            if (!user.getText().toString().equals("") || !password.getText().toString().equals("")) {
                loadingDialog = new LoadingDialog(login.this);
                loadingDialog.setMessage("正在登录....");
                loadingDialog.show();
                Login();
            } else {
                Toast.makeText(login.this, "账号或密码有误", Toast.LENGTH_SHORT).show();
                return;
            }
        });
        checkBox.setOnCheckedChangeListener((compoundButton, b) -> {
            if (checkBox.isChecked()) {
                jz = getSharedPreferences("mm", Context.MODE_PRIVATE);//1.通过上下文得到
                SharedPreferences.Editor editor = jz.edit();  //2.通过SharedPreferences得到编辑器用于保存数据
                editor.putString("user", user.getText().toString());
                editor.putString("password", password.getText().toString()); //3.键值对的形式保存数据
                editor.putString("b", "1");
                editor.commit();
            } else {
                jz = getSharedPreferences("mm", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = jz.edit();
                editor.putString("b", "0");
                editor.commit();
            }
        });
//        HksPower.uhf_power(1);//上电
    }

    private void Login() {
        Map<String, String> map = new HashMap<>();
        map.put("account", user.getText().toString());
        map.put("password", password.getText().toString());
        myOkHttp.post(url, map, new MyOkHttp.requestMessage() {
            @Override
            public void requestFail() {
                showToast("连接服务器失败");
                canDialog();
            }

            @Override
            public void requestSuccess(Response response) throws IOException {
                Gson gson = new Gson();
                assert response.body() != null;
                String data = response.body().string();
                LogUtils.d(data);
                try {
                    LoginJavaBean loginJavaBean = gson.fromJson(data, LoginJavaBean.class);
                    show(loginJavaBean);
                } catch (Exception e) {
                    e.printStackTrace();
                    showToast("数据解析失败");
                    canDialog();
                }
            }
        });
    }

    private void show(final LoginJavaBean loginJavaBean) {
        try {
            if (loginJavaBean.getState().equals("1")) {
                setSince(loginJavaBean);
                Since_case.set().setSource(loginJavaBean.getSource());
                final LoginJavaBean.UserBean userBean = loginJavaBean.getUser();
                jz = getSharedPreferences("mm", Context.MODE_PRIVATE);//1.通过上下文得到
                SharedPreferences.Editor editor1 = jz.edit();  //2.通过SharedPreferences得到编辑器用于保存数据
                editor1.putString("user", user.getText().toString());
                editor1.putString("password", password.getText().toString()); //3.键值对的形式保存数据
                editor1.putString("roleid", userBean.getRoleId());//角色。1是管理员，2是站长
                editor1.putString("deptid", String.valueOf(userBean.getDeptId()));
                editor1.putString("version", String.valueOf(loginJavaBean.getVersion()));//等级
                editor1.putString("name", userBean.getName());
                editor1.putString("id", String.valueOf(userBean.getUserId()));
                editor1.apply();
                //roleid 角色id，deptid部门id，id用户id ，name名字
                showToast("登录成功");
                Since_case.set().setONorOff(true);
                Intent inten = new Intent(login.this, HomeActivity.class);
                startActivity(inten);
                finish();
            }
            if (loginJavaBean.getState().equals("0")) {
                showToast("账号或密码错误");
                return;
            }
            if (loginJavaBean.getState().equals("500")) {
                showToast("服务器异常");
            }
        } catch (Exception e) {
            showToast("登录失败，请重试");
            e.printStackTrace();
        }
        finally {
            canDialog();
        }
    }

    private List<String> listString = new ArrayList<>();

    private void setSince(LoginJavaBean loginJavaBean) {
        if (loginJavaBean.getPDA_ASSETS().equals("1")) {
            listString.add("0");
        } else listString.add("1");

        if (loginJavaBean.getPDA_EQUIPMENT().equals("1")) {
            listString.add("0");
        } else listString.add("1");

        if (loginJavaBean.getPDA_INSPECTION().equals("1")) {
            listString.add("0");
        } else listString.add("1");

        if (loginJavaBean.getPDA_WAREHOUSING().equals("1")) {
            listString.add("0");
        } else listString.add("1");

        if (loginJavaBean.getPDA_RECEIVE().equals("1")) {
            listString.add("0");
        } else listString.add("1");

        if (loginJavaBean.getPDA_CHECK().equals("1")) {
            listString.add("0");
        } else listString.add("1");

        if (loginJavaBean.getPDA_RETURN().equals("1")) {
            listString.add("0");
        } else listString.add("1");

        if (loginJavaBean.getPDA_ALLOT().equals("1")) {
            listString.add("0");
        } else listString.add("1");

        if (loginJavaBean.getPDA_SCRAPPED().equals("1")) {
            listString.add("0");
        } else listString.add("1");

        if (loginJavaBean.getPDA_REPAIR().equals("1")) {
            listString.add("0");
        } else listString.add("1");

        if (loginJavaBean.getPDA_MAINTENANCE().equals("1")) {
            listString.add("0");
        } else listString.add("1");

        if (loginJavaBean.getPDA_SERVICE().equals("1")) {
            listString.add("0");
        } else listString.add("1");

        if (loginJavaBean.getPDA_INQUIRE().equals("1")) {
            listString.add("0");
        } else listString.add("1");

        if (loginJavaBean.getPDA_TASK().equals("1")) {
            listString.add("0");
        } else listString.add("1");

        if (loginJavaBean.getPDA_EXCEPTION().equals("1")) {
            listString.add("0");
        } else listString.add("1");
        Since_case.set().setListString(listString);
    }

    private void inview() {
        setip = (TextView) findViewById(R.id.setip);
        setip.setOnClickListener(v -> {
            final MyAlertInputDialog myAlertInputDialog = new MyAlertInputDialog(login.this).builder()
                    .setTitle("修改IP地址")
                    .setEditText("");
            myAlertInputDialog.setEditText(Ip_Set.IP);
            myAlertInputDialog.setPositiveButton("确认", v1 -> {
                if (!myAlertInputDialog.getResult().equals("")) {
                    jz = getSharedPreferences("mm", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = jz.edit();
                    editor.putString("ipip", myAlertInputDialog.getResult());
                    editor.commit();
                    Ip_Set ipSet = new Ip_Set();
                    ipSet.setIP(myAlertInputDialog.getResult());
                    url = "http://" + Ip_Set.IP + "/api/login";
                    myAlertInputDialog.dismiss();
                    Log.i("ipipip", Ip_Set.IP);
                } else {
                    showToast("ip地址不可为空");
                }
            }).setNegativeButton("取消", v12 -> myAlertInputDialog.dismiss());
            myAlertInputDialog.show();
        });
        user = (EditText) findViewById(R.id.et_userName);
        password = (EditText) findViewById(R.id.et_password);
        checkBox = (CheckBox) findViewById(R.id.cb_checkbox);
        login = (Button) findViewById(R.id.btn_login);
    }

    private void canDialog() {
        if (loadingDialog != null) {
            if (loadingDialog.isShowing()) {
                runOnUiThread(() -> {
                    loadingDialog.cancel();
                });
            }
        }
    }

    public boolean isConnByHttp() {

        boolean isConn = false;
        URL url;
        HttpURLConnection conn = null;

        try {
            url = new URL("http://" + Ip_Set.IP);
            conn = (HttpURLConnection) url.openConnection();
            // conn.setHeader("Range","bytes="+"");
            conn.setConnectTimeout(1000 * 8);
            if (conn.getResponseCode() == 200) {
                isConn = true;
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block

        } catch (IOException e) {
            // TODO Auto-generated catch block

        } finally {
            conn.disconnect();
        }
        return isConn;
    }

    @Override
    public void onBackPressed() {
        if (i == 1) {
            finish();
        }
        i = i + 1;
        Toast.makeText(login.this, "再按一次退出", Toast.LENGTH_SHORT).show();
    }

    private void showToast(final String data) {
        runOnUiThread(() -> Toast.makeText(getApplicationContext(), data, Toast.LENGTH_SHORT).show());

    }
}
